import Editor from '@components/editor';
import Layout from '@components/layout';
import * as WorkApi from '@lib/api/work';
import { Button, Card, Form, Icon, Input, message, Spin } from 'antd';
import Router from 'next/router';
import * as React from 'react';

interface IUpgradeState {
	code: string;
	detail: string;
	loading: boolean;
	name?: string;
}

interface IUpgradeProps {
	id: number;
}

class Upgrade extends React.Component<IUpgradeProps, IUpgradeState> {
	static getInitialProps(param: any) {
		return {
			id: param.query.id
		};
	}
	constructor(props: any) {
		super(props);
		this.state = {
			code: "",
			detail: "",
			loading: false
		}
		this.onSubmit = this.onSubmit.bind(this);
		this.onInputChange = this.onInputChange.bind(this);
	}
	public async componentDidMount() {
		const res = await WorkApi.Get(this.props.id, true);
		if (!(res instanceof Error)) {
			this.setState({
				name: res.work.name
			});
		}
	}
	public onInputChange(e: string | React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, name?: string) {
		const res: any = Object.assign({}, this.state);
		if (typeof (e) === "string") {
			if (typeof (name) === "string") res[name] = e;
		} else {
			res[e.target.name] = e.target.value;
		}
		this.setState(res);
	}
	public async onSubmit(e: React.FormEvent) {
		e.preventDefault();
		this.setState({
			loading: true
		});
		const res = await WorkApi.Upgrade({
			id: this.props.id,
			code: this.state.code,
			detail: this.state.detail
		});
		if (res instanceof Error) {
			message.error(res.message);
		} else {
			message.success('提交成功');
			Router.push("/my/work");
		}
		this.setState({
			loading: false
		});
	}
	public render() {
		const codeValidate: any = (this.state.code === "" || /^(\w+)$/.test(this.state.code)) ? {} : {
			validateStatus: "error",
			help: "分享码无效。若有多个分享码请写在详情中"
		};
		return (
			<Layout title="更新作品">
				<Card title="更新作品">
					<Spin spinning={this.state.loading}>
						<Form layout="horizontal" onSubmit={this.onSubmit}>
							<Form.Item label="名称" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
								{this.state.name || <Icon type="loading" />}
							</Form.Item>
							<Form.Item label="详情（Markdown）" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} help="不建议在此处上传图片">
								<Editor value="" onChange={(text: string) => this.onInputChange(text, 'detail')} />
							</Form.Item>
							<Form.Item label="分享码" labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} {...codeValidate}>
								<Input name="code" onChange={this.onInputChange} required />
							</Form.Item>
							<Form.Item wrapperCol={{ offset: 4, span: 20 }}>
								<Button type="primary" htmlType="submit">提交</Button>
							</Form.Item>
						</Form>
					</Spin>
				</Card>
			</Layout>
		);
	}
}

export default Upgrade;